<?php

namespace teach\service;

use Yii;

/**
 * 模式2情况下
 * 根据星级别给用户分佣
 * Class StarModel
 * @package teach\service
 */
class StarModel
{
    public function payAll($oid, $mid, $uid)
    {
        //获取提成参数
        $distribution = $this->distribution($mid);

        //获取此条订单
        $order = $this->sureOrder($oid, $mid, $uid);

        if (!$order) {
            return false;
        }

        //如果账单小于1元 将订单改为已结算
        if (($order['total_fee'] + $order['recharge']) < 1) {
            // 后台将订单改为已处理 已结算
            $this->dealPay($order['p_id']);
            return true;
        }

        //商家自己购买自己的产品
        if ($mid == $uid) {
            //  后台将订单改为已处理 已结算
            $this->dealPay($order['p_id']);
            return true;
        }

        //获取下单用户
        $user = $this->userOne($uid);

        //用户绑定了商家 没有上级
        if ($user['mall_superior'] == 0) {
            // 后台将订单改为已处理 已结算
            //$this->dealPay($order['p_id']);
            return true;
        }

        //用户只有一个上级
        if ($user['mall_top'] == 0) {
            //将佣金打给上级
            $this->superior($uid, $user['mall_superior'], $mid, $order['out_trade_no'], $order['logistic_fee'], ($order['total_fee'] + $order['recharge']), $order['p_id'], $distribution);
            return true;
        } else {
            //佣金打给上级跟上上级
            $this->top($uid, $user['mall_superior'], $user['mall_top'], $mid, $order['out_trade_no'], $order['logistic_fee'], ($order['total_fee'] + $order['recharge']), $order['p_id'], $distribution);
            return true;
        }

    }

    /**
     * 三个层级时，给上级上上级发佣金
     * @param $uid
     * @param $sid
     * @param $tid
     * @param $mid
     * @param $out_trade_no
     * @param $logistic_fee
     * @param $total_fee
     * @param $p_id
     * @param $distribution
     */
    private function top($uid, $sid, $tid, $mid, $out_trade_no, $logistic_fee, $total_fee, $p_id, $distribution)
    {
        //上级用户
        $super_user = $this->userOne($sid);
        //判断上级用户的星级
        switch ($super_user['score_total'])
        {
            case $super_user['score_total'] >= 0 && $super_user['score_total'] < $distribution['three_star_score']:
                $star = $distribution['three_star'];
                $star_name = $distribution['three_star_name'];
                $percent_one = $distribution['three_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['five_star_score']:
                $star = $distribution['three_star'];
                $star_name = $distribution['three_star_name'];
                $percent_one = $distribution['three_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['six_star_score']:
                $star = $distribution['five_star'];
                $star_name = $distribution['five_star_name'];
                $percent_one = $distribution['five_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['seven_star_score']:
                $star = $distribution['six_star'];
                $star_name = $distribution['six_star_name'];
                $percent_one = $distribution['six_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] >= $distribution['seven_star_score']:
                $star = $distribution['seven_star'];
                $star_name = $distribution['seven_star_name'];
                $percent_one = $distribution['seven_star_one'];
                $status_bill = 2;
                break;
            default:
                $star = 0;
                $star_name = '发生异常';
                $percent_one = 0;
                $status_bill = 3;
        }

        //上上级用户
        $top_user = $this->userOne($tid);

        //判断上级用户的星级
        switch ($top_user['score_total'])
        {
            case $top_user['score_total'] >= 0 && $top_user['score_total'] < $distribution['three_star_score']:
                $star_two = $distribution['three_star'];
                $star_name_two = $distribution['three_star_name'];
                $percent_two = $distribution['three_star_two'];
                $status_bill_two = 2;
                break;
            case $top_user['score_total'] < $distribution['five_star_score']:
                $star_two = $distribution['three_star'];
                $star_name_two = $distribution['three_star_name'];
                $percent_two = $distribution['three_star_two'];
                $status_bill_two = 2;
                break;
            case $top_user['score_total'] < $distribution['six_star_score']:
                $star_two = $distribution['five_star'];
                $star_name_two = $distribution['five_star_name'];
                $percent_two = $distribution['five_star_two'];
                $status_bill_two = 2;
                break;
            case $top_user['score_total'] < $distribution['seven_star_score']:
                $star_two = $distribution['six_star'];
                $star_name_two = $distribution['six_star_name'];
                $percent_two = $distribution['six_star_two'];
                $status_bill_two = 2;
                break;
            case $top_user['score_total'] >= $distribution['seven_star_score']:
                $star_two = $distribution['seven_star'];
                $star_name_two = $distribution['seven_star_name'];
                $percent_two = $distribution['seven_star_two'];
                $status_bill_two = 2;
                break;
            default:
                $star_two = 0;
                $star_name_two = '发生异常';
                $percent_two = 0;
                $status_bill_two = 3;
        }

        //上级用户佣金
        $total_fee_superior = ($total_fee - $logistic_fee) * $percent_one;

        //上上级用户佣金
        $total_fee_top = ($total_fee - $logistic_fee) * $percent_two;

        //给上级发送佣金
//        $this->topOne($total_fee_superior, $total_fee, $sid);

        //记录入库
        $this->record($sid, $uid, $mid, 1, "一级分销", $out_trade_no, $total_fee_superior, time(), $super_user['score'], $status_bill, $star, $star_name, $percent_one);

        //TODO 给上级发送模板消息 先查找上级，拿到openid ，然后发送消息
        $redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();

        $reason_super = "您推荐的下级用户购买了产品";
        $tip = "您获得暂未结算积分,可到商城查看";

        $WeChat = new \teach\components\WeChat();
        while (true) {
            $formid = $redis->rpop("formid_{$super_user['openid']}");
            $status = $WeChat->sendMsg($SendWeChatMessage->payGoods($super_user['openid'], $formid, $total_fee_superior,$reason_super,$tip));
            if ($status['errcode'] == 0 || $formid == false) {
                break;
            }
        }


        //给上上级发送佣金
//        $this->topTwo($total_fee_top, $total_fee, $tid);

        //记录入库
        $this->record($tid, $uid,$mid, 2, "二级分销", $out_trade_no, $total_fee_top, time(), $super_user['score'], $status_bill_two, $star_two, $star_name_two, $percent_two);

        //TODO 给上上级发送模板消息

//        $WeChat = new \teach\components\WeChat();
        $reason_top  = "您推荐的下下级用户购买了产品";
        while (true) {
            $formid_top = $redis->rpop("formid_{$top_user['openid']}");
            $status_top = $WeChat->sendMsg($SendWeChatMessage->payGoods($top_user['openid'], $formid_top, $total_fee_top, $reason_top,$tip));
            if ($status_top['errcode'] == 0 || $formid_top == false) {
                break;
            }
        }

        //将pay表改为已处理 未结算3
        $this->dealPayLow($p_id);


    }

    //只有一个上级时，给上级打入佣金
    private function superior($uid, $mall_superior_id, $mid, $out_trade_no, $logistic_fee, $total_fee, $p_id, $distribution)
    {
        //查找上级用户
        $super_user = $this->userOne($mall_superior_id);

        //判断上级用户的星级
        switch ($super_user['score_total'])
        {
            case $super_user['score_total'] >= 0 && $super_user['score_total'] < $distribution['three_star_score']:
                $star = $distribution['three_star'];
                $star_name = $distribution['three_star_name'];
                $percent = $distribution['three_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['five_star_score']:
                $star = $distribution['three_star'];
                $star_name = $distribution['three_star_name'];
                $percent = $distribution['three_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['six_star_score']:
                $star = $distribution['five_star'];
                $star_name = $distribution['five_star_name'];
                $percent = $distribution['five_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] < $distribution['seven_star_score']:
                $star = $distribution['six_star'];
                $star_name = $distribution['six_star_name'];
                $percent = $distribution['six_star_one'];
                $status_bill = 2;
                break;
            case $super_user['score_total'] >= $distribution['seven_star_score']:
                $star = $distribution['seven_star'];
                $star_name = $distribution['seven_star_name'];
                $percent = $distribution['seven_star_one'];
                $status_bill = 2;
                break;
            default:
                $star = 0;
                $star_name = '发生异常';
                $percent = 0;
                $status_bill = 3;
        }

        if ($status_bill == 3) {
            return false;
        }
        //上级用户得到的佣金
        $total_fee_superior = ($total_fee - $logistic_fee) * $percent;
//        $this->superAmount($total_fee_superior, $total_fee, $mall_superior_id);

        //将pay表改为已处理 未结算3
        $this->dealPayLow($p_id);

        //将打入的金额记录入表 status= 2 表示未结算
        $this->record($mall_superior_id, $uid, $mid, 1, "一级分销", $out_trade_no, $total_fee_superior, time(), $super_user['score'], $status_bill, $star, $star_name, $percent);

        //TODO 发送模板消息
        $redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();
        $tip = "您获得暂未结算积分,可到商城查看";
        $reason = "您推荐的下级购买了产品";

        $WeChat = new \teach\components\WeChat();
        while (true) {
            $formid = $redis->rpop("formid_{$super_user['openid']}");
            $status = $WeChat->sendMsg($SendWeChatMessage->payGoods($super_user['openid'], $formid, $total_fee_superior,$reason,$tip));
            if ($status['errcode'] == 0 || $formid == false) {
                break;
            }
        }

        return true;
    }

    /**
     *  记录分配
     * @param $uid
     * @param $sid
     * @param $mid
     * @param $direct
     * @param $direct_text
     * @param $out_trade_no
     * @param $amount
     * @param $create_time
     * @param $status
     * @param $score
     * @param $star
     * @param $star_name
     * @param $percent
     * @return int
     */
    private function record($uid, $sid, $mid, $direct, $direct_text, $out_trade_no, $amount, $create_time, $score, $status, $star, $star_name, $percent)
    {
        $map = [
            'uid' => $uid,
            'sid' => $sid,
            'mid' => $mid,
            'direct' => $direct,
            'direct_text' => $direct_text,
            'out_trade_no' => $out_trade_no,
            'amount' => $amount,
            'create_time' => $create_time,
            'status' => $status,
            'score' => $score,
            'star' => $star,
            'star_name' => $star_name,
            'mall_model' => 2,
            'percent' => $percent,
        ];
        return Yii::$app->db->createCommand()->insert('mall_bill', $map)->execute();
    }

    /**
     * 查找佣金
     * @param $mid
     * @return array|false
     */
    private function distribution($mid)
    {
        $sql = "SELECT * FROM mall_distribution WHERE state = 2 AND mid = {$mid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 查找一条订单
     * @param $oid
     * @param $mid
     * @param $uid
     * @return array|false
     */
    private function sureOrder($oid, $mid, $uid)
    {
        $sql = "SELECT p.id AS p_id, p.out_trade_no, p.total_fee, p.status AS p_status, o.id AS o_id, o.mid, o.uid, o.openid, o.out_trade_no, o.total_fee, o.logistic_fee, o.status AS o_status, o.recharge FROM mall_pay AS p LEFT JOIN mall_order AS o ON p.out_trade_no = o.out_trade_no WHERE p.status = 1 AND o.id = {$oid} AND o.mid = {$mid} AND o.uid = {$uid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 将mall_pay 改为已结算2
     * @param $p_id
     * @return int
     */
    private function dealPay($p_id)
    {
        $sql = "UPDATE mall_pay SET status = 2 WHERE id = {$p_id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * @param $p_id 3表示未结算
     * @return int
     */
    private function dealPayLow($p_id)
    {
        $sql = "UPDATE mall_pay SET status = 3 WHERE id = {$p_id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 获取下单用户
     * @param $uid
     * @return array|false
     */
    private function userOne($uid)
    {
        $sql = "SELECT mall_superior, openid, mall_top, mall_id, score, score_total FROM edu_user WHERE id = {$uid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }
}